package com.lv.suyiyong.hfr.ui

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Build
import android.view.View
import android.view.View.OnClickListener
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.CollectionUtils
import com.blankj.utilcode.util.GsonUtils
import com.bumptech.glide.Glide
import com.google.gson.reflect.TypeToken
import com.jeremyliao.liveeventbus.LiveEventBus
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.lv.common.base.BaseActivity
import com.lv.common.imp.UploadFileListener
import com.lv.common.ktx.LoadSrc
import com.lv.common.ktx.initSingleClickListener
import com.lv.common.ktx.isJson
import com.lv.common.network.model.DataResult
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.AnimationUtils
import com.lv.common.utils.FileUtils
import com.lv.common.utils.MyUtils
import com.lv.common.utils.PermissionXUtils
import com.lv.common.utils.PermissionXUtilsCallback
import com.lv.common.utils.StatusBarUtil
import com.lv.common.utils.YgxNetUtilsKt
import com.lv.common.utils.picengine.CompressEngine
import com.lv.common.utils.picengine.GlideEngine
import com.lv.common.utils.showToast
import com.lv.common.widget.keyboard.KeyboardUtil
import com.lv.service.bean.CategoryMoreBean
import com.lv.service.bean.CategorySubBean
import com.lv.service.bean.ClientItemBean
import com.lv.service.bean.CommonTab
import com.lv.service.bean.DisplayFacBean
import com.lv.service.bean.DisplayPro
import com.lv.service.bean.NameBean
import com.lv.service.bean.TVIVItemBean
import com.lv.service.bean.TelSecondCategory
import com.lv.service.bean.TelThirdCategory
import com.lv.service.dialog.CategoryImageSelectedPopupView
import com.lv.service.dialog.ShowProvinceSelectedBottomPopupView
import com.lv.service.event.ClientStateEvent
import com.lv.service.event.CompanyStateEvent
import com.lv.service.model.EditorViewModel
import com.lv.service.model.ServiceViewModel
import com.lv.service.net.ClientHFRReqBody
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.room.address.AddressDbHelper
import com.lv.service.room.category.CategoryBean
import com.lv.service.room.category.CategoryDbHelper
import com.lv.service.room.company.CompanyDraftItemBean
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.databinding.ActivityHfrOpenClientBinding
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupPosition
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.androidx.viewmodel.ext.android.viewModel


/**
 * 作者： ygx
 * 创建日期：2023/4/12 2:04 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ------------------------------------------------开户------------
 * 描述：申请开户
 */
@Route(path = ARoutUtils.OpenClientHFRActivity)
class OpenClientHFRActivity : BaseActivity<ActivityHfrOpenClientBinding>(),
    OnClickListener {

    @Autowired(name = "item")
    @JvmField
    var mIntentItem: CompanyDraftItemBean? = null
    private var mIsOpen = false
    private var mProvinceIsOpen = false
    private var keyboardUtil: KeyboardUtil? = null
    private val mBeans = mutableListOf<LocalMedia?>()//选择的图像

    //    private val mTempBeans = mutableListOf<LocalMedia?>()//选择的图像保存草稿时要删除
//    private val mTempDeleteFactoryBeans = ArrayList<String>()//工厂展示保存草稿时要删除
    private val mFactoryBeans = ArrayList<TVIVItemBean>()//工厂展示
    private val mAddressBeans = ArrayList<CommonTab>()//地址选择
    private val mSelectedAddressBeans = ArrayList<CommonTab>()//地址选择
    private val mBnames = ArrayList<String>()//主营
    private var mUserInfo: UserInfo? = null
    private var mDetailsAddress: String = ""
    private var mProvince: String = ""
    private var mCity: String = ""
    private var mArea: String = ""
    private var mTown: String = ""

    //    private val mDefaultBorderBean = FactoryBorderItemBean(
//        "18",
//        "https://suyiyong.oss-cn-hangzhou.aliyuncs.com/1231/newkuang/7-1-1.png",
//        "https://suyiyong.oss-cn-hangzhou.aliyuncs.com/1231/newkuang/7-1.png",
//        "upleft",
//        "293",
//        "105",
//        "1",
//        "D2D2D2",
//        "0",
//        "5", isspecially = "0"
//    )
    private val mEditorViewModel by viewModels<EditorViewModel>()
    private val viewModel: ServiceViewModel by viewModel()
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    override fun getLayoutRes() = R.layout.activity_hfr_open_client
    override fun initView() {
        super.initView()
        initStatusBar(this, true, true)
        ARouter.getInstance().inject(this)
        mBinding.apply {
            StatusBarUtil.setHeightAndPadding(this@OpenClientHFRActivity, titleBar)
            titleBar.onClickBackIcon { finish() }
            titleBar.setTitle("开通免费店铺")

            editorVM = mEditorViewModel
            initSingleClickListener(
                tvSubmit,
                viewLogo,
                viewBnames,
                viewAddress,
                viewProvince,
                viewFactory,
                scrollView,
                viewCategory
            )
        }
    }


    override fun initConfig() {
        super.initConfig()
        UserDbHelper.getLiveUserInfo(this@OpenClientHFRActivity).observeKt {
            it?.let {
                mUserInfo = it
            }
        }
        lifecycleScope.launch {

            this.launch {
                //发行
                val datas =
                    AddressDbHelper.getFindAllAddressSuspend(this@OpenClientHFRActivity)
                datas?.let {
                    mAddressBeans.clear()
                    for (i in 0 until datas.size) {
                        val element = datas[i]
                        val name = element.name
                        mAddressBeans.add(CommonTab(name = name))
                    }
                }
            }
            this.launch {
                //所有分类
                val mAllCategory =
                    CategoryDbHelper.getFindAllCategorySuspend(this@OpenClientHFRActivity)
                mAllCategory?.let {
                    if (CollectionUtils.isNotEmpty(mAllCategory)) {
                        initCategoryDate(mAllCategory)
                    }

                }
            }


        }
    }

    private val mCategoryBean = mutableListOf<TelSecondCategory>()
    private val mSelectedCategoryBean = mutableListOf<TelSecondCategory>()

    /**
     * 切换数据源
     */
    private fun initCategoryDate(beans: List<CategoryBean>) {

        mCategoryBean.clear()
        beans.let {
            beans.forEach { fristItem ->
                val telSecondCategories = fristItem.telSecondCategories
                telSecondCategories?.let {
                    mCategoryBean.add(
                        TelSecondCategory(
                            fristItem.fcaid,
                            "",
                            "",
                            fristItem.name,
                            0,
                            0,
                            null,
                            false,
                            true
                        )
                    )
                    for (item in telSecondCategories) {
                        val telThirdCategories = item.telThirdCategories
                        val telthird = mutableListOf<TelThirdCategory>()
                        telThirdCategories?.let {
                            for (tel in telThirdCategories) {
                                telthird.add(
                                    TelThirdCategory(
                                        tel.id,
                                        item.fcaid.toString(),
                                        tel.image,
                                        tel.name,
                                        tel.postion,
                                        tel.postionSalf,
                                        false,
                                        false
                                    )
                                )
                            }
                        }
                        mCategoryBean.add(
                            TelSecondCategory(
                                item.fcaid,
                                item.id,
                                item.image,
                                item.name,
                                item.secaid,
                                item.seq,
                                telthird,
                                false,
                                false
                            )
                        )
                    }

                }
            }
        }

    }

    override fun initEvents() {
        super.initEvents()
        mBinding.etIndentification.setOnTouchListener { _, _ ->
            keyboardUtil = KeyboardUtil(
                this,
                mBinding.etIndentification,
                mBinding.llKeyboard,
                mBinding.keyboardView
            )
            keyboardUtil?.hideSoftInputMethod()
            keyboardUtil?.showKeyboard()
//            keyboardUtil?.changeKeyboard(true)
            false
        }
    }

    override fun initData() {
        super.initData()

        if (mIntentItem != null) {
            mEditorViewModel.obCpname.set(mIntentItem?.name)
            val logoMedia = mIntentItem?.logoMedia
            if (!logoMedia.isNullOrEmpty()) {
                val logo = logoMedia[0] ?: ""
                mBeans.clear()
//                mTempBeans.clear()
                val exit = FileUtils.checkFileExits(logo)
                if (exit) {
                    val media = LocalMedia()
                    media.compressPath = logo
                    media.path = logo
                    media.realPath = logo
                    mBeans.add(media)
//                    mTempBeans.add(media)
                    mBinding.ivLogo.LoadSrc(logo)
                }
            }
            mEditorViewModel.obName.set(mIntentItem?.identification)
            mEditorViewModel.obPhone.set(mIntentItem?.phone)
            val bnames = mIntentItem?.bnames
            if (!bnames.isNullOrEmpty() && bnames.isJson()) {
                mBnames.clear()
                try {
                    val jsonType = object : TypeToken<List<String>>() {}.type
                    val mBname: List<String>? =
                        GsonUtils.fromJson(bnames, jsonType)
                    if (!mBname.isNullOrEmpty()) {
                        mBnames.addAll(mBname)
                        var bNames = ""
                        mBnames.forEach { item ->
                            bNames = "$bNames、$item"
                        }
                        if (bNames.startsWith("、")) {
                            bNames = bNames.drop(1)
                        }
                        mBinding.tvBname.text = bNames
                    }

                } catch (e: Exception) {
                }
            }
            mEditorViewModel.paramsSeting.postValue(mBnames.isNotEmpty())

            mProvince = mIntentItem?.province ?: ""
            mCity = mIntentItem?.city ?: ""
            mArea = mIntentItem?.area ?: ""
            mTown = mIntentItem?.prefecture ?: ""
            mDetailsAddress = mIntentItem?.address ?: ""
            mBinding.tvAddress.text = "$mProvince$mCity$mArea$mTown$mDetailsAddress"
            mEditorViewModel.addressShow.postValue(mDetailsAddress.isNotEmpty())

            val category = mIntentItem?.category
            mSelectedCategoryBean.clear()
            category?.let { ca ->
                mSelectedCategoryBean.addAll(ca)
                mBinding.tvCategory.text = "已设置"
            }
            val book = mIntentItem?.book
            val split = book?.split(",")
            mSelectedAddressBeans.clear()
            split?.forEach { item ->
                mSelectedAddressBeans.add(CommonTab("", "", item, 0, true))
            }
            if (mSelectedAddressBeans.isNotEmpty()) {
                mBinding.tvProvince.text = "已设置"
            }
            mFactoryBeans.clear()
//            mTempDeleteFactoryBeans.clear()
            val factoryMedia = mIntentItem?.factoryMedia
            var picCount = 0
            factoryMedia?.forEach { factory ->
                val image = factory.image
                val exit = FileUtils.checkFileExits(image?.compressPath)
                if (exit) {
                    mFactoryBeans.add(factory)
//                    mTempDeleteFactoryBeans.add(factory.image?.compressPath ?: "")
                    if (factory.type == "0") {
                        picCount++
                    }
                }
            }
            if (picCount > 1) {
                mBinding.tvFactory.text = "已设置"
            }
            mEditorViewModel.moreTypeMedia.postValue(mFactoryBeans)

        }
    }


    override fun onClick(v: View?) {
        keyboardUtil?.hideKeyboard()
        when (v?.id) {
            R.id.scroll_view -> {
                keyboardUtil?.hideKeyboard()
            }

            R.id.view_logo -> {
                checkPermission()
            }

            R.id.view_bnames -> {
                ARouter.getInstance().build(ARoutUtils.ManagerBnamesActivity)
                    .withSerializable("bnames", mBnames)
                    .navigation(this, 4)

            }

            R.id.view_address -> {
                ARouter.getInstance().build(ARoutUtils.AddressCommonActivity)
                    .withString("title", "地址")
                    .withString("hint", "请输入详细地址")
                    .withString("province", mProvince)
                    .withString("city", mCity)
                    .withString("area", mArea)
                    .withString("town", mTown)
                    .withString("content", mDetailsAddress)
                    .navigation(this, 5)
            }

            R.id.view_category -> {//行业
                showCategoryBottomDialog()
            }

            R.id.view_province -> {//展示省份
                ShowProvinceSelectedPopupView()
            }

            R.id.view_factory -> {//工厂展示
                val dis = arrayListOf<DisplayFacBean>()
                mFactoryBeans.forEach { itemFactory ->
                    val dispay =
                        DisplayFacBean(
                            itemFactory.image?.realPath,
                            itemFactory.type,
                            itemFactory.image?.realPath,
                            itemFactory.width, itemFactory.height
//                            , itemFactory.border
                        )
                    dis.add(dispay)
                }
                ARouter.getInstance().build(ARoutUtils.ShowFactoryActivity)
                    .withString("type", "1")
                    .withParcelableArrayList("items", dis).navigation(this, 8)
            }

            R.id.tv_submit -> {
                aliUpNet()
//                ARouter.getInstance().build(ARoutUtils.OrderPaySuccessActivity)
//                    .withString("otherid", "data?.id")
//                    .withString("state", "11").navigation()
//                finish()
            }

//            R.id.tv_save -> {
//                saveDataBase()
//            }
        }
    }

    private fun checkPermission() {
        val permissions = mutableListOf(
            Manifest.permission.CAMERA,
        )
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions.add(Manifest.permission.READ_MEDIA_IMAGES)
//            permissions.add(Manifest.permission.READ_MEDIA_AUDIO)
//            permissions.add(Manifest.permission.READ_MEDIA_VIDEO)
        } else {
            permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE)
        }
        PermissionXUtils.checkPermissBefore(
            this@OpenClientHFRActivity,
            permissions,
            "请授予相机、存储权限，以便使用相机拍摄或在手机相册中选择图片",
            callback = object : PermissionXUtilsCallback {
                override fun permissionCallback(
                    allGranted: Boolean,
                    grantedList: List<String?>,
                    deniedList: List<String?>
                ) {
                    if (allGranted) {
                        showPicSelector()
                    }
                }
                override fun fotPermsission() {

                }
            })
    }

    private fun showPicSelector() {

        PictureSelector.create(this@OpenClientHFRActivity)
            .openGallery(SelectMimeType.ofImage())//图库显示的类型
            .setImageEngine(GlideEngine.createGlideEngine())
            .setCompressEngine(CompressEngine.createCompressEngine())
            .setMaxSelectNum(1)//最大图片数
//            .setMaxVideoSelectNum(1)//最大视频数
            .setMinSelectNum(1)
            .setImageSpanCount(4)
            .isMaxSelectEnabledMask(true)//不可点击时，是否显示朦层
            .isPreviewImage(true) // 是否可预览图片
            .isDisplayCamera(true) // 是否显示拍照按钮
            .isOriginalSkipCompress(true) // 是否压缩
            .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
//            .setSelectedData(mBeans)
//            .isWithSelectVideoImage(false)//是否可以同时选择视频和图片
            .forResult(object : OnResultCallbackListener<LocalMedia?> {
                override fun onResult(result: ArrayList<LocalMedia?>?) {
                    mBeans.clear()
                    result?.let {
                        if (result.isNotEmpty()) {
                            mBeans.addAll(result)
                            Glide.with(this@OpenClientHFRActivity).load(result[0]?.realPath)
                                .into(mBinding.ivLogo)
                        }
                    }

                }

                override fun onCancel() {}
            })
    }

    private var mCategoryPopupView: CategoryImageSelectedPopupView? = null

    /**
     * @param
     */
    private fun showCategoryBottomDialog() {
        mCategoryPopupView = null
        if (mCategoryPopupView == null) {
            mCategoryPopupView = CategoryImageSelectedPopupView(
                this, mIsOpen,
                mCategoryBean,
                mSelectedCategoryBean, true,
            ) { position, data ->
                mSelectedCategoryBean.clear()
                mSelectedCategoryBean.addAll(data)
                if (mSelectedCategoryBean.isNotEmpty()) {
                    mBinding.tvCategory.text = "已设置"
                    mEditorViewModel.categorySelected.postValue(true)
                } else {
                    mBinding.tvCategory.text = ""
                    mEditorViewModel.categorySelected.postValue(false)
                }

//                var categoryName = ""
//                mSelectedCategoryBean.forEach { item ->
//                    val fcaid = item.fcaid
//                    val cate = mCategoryBean.filter { category -> category.fcaid == fcaid }
//                    var name = item.name
//                    if (cate.isNotEmpty()) {
//                        name = "${cate[0].name}-${item.name}"
//                    }
//                    categoryName = "$categoryName、$name"
//                }
//                if (categoryName.startsWith("、")) {
//                    categoryName = categoryName.drop(1)
//                }
//                mBinding?.tvCategory?.text = categoryName
            }
        }

        XPopup.Builder(this)
            .isViewMode(true)//对于只使用一次的弹窗，推荐设置这个true
            .popupPosition(PopupPosition.Bottom)
            .asCustom(mCategoryPopupView)
            .show()

        mCategoryPopupView?.setOnSwitchListener { position, data ->
            ARouter.getInstance().build(ARoutUtils.SwitchCommonActivity)
                .withString("title", "多分类展示")
                .withString("content", "多分类展示")
                .withString("dec", "开启“多分类展示”后，可直接返回上一页，选择多个分类。")
                .withBoolean("isOpen", mIsOpen)
                .navigation(this, 6)
        }
    }

    private var mProvincePopupView: ShowProvinceSelectedBottomPopupView? = null

    /**
     * @param
     */
    private fun ShowProvinceSelectedPopupView() {
        mProvincePopupView = null
        if (mProvincePopupView == null) {
            mProvincePopupView =
                ShowProvinceSelectedBottomPopupView(
                    this, mProvinceIsOpen,
                    mAddressBeans, mSelectedAddressBeans, true
                ) { position, data ->
                    mSelectedAddressBeans.clear()
                    mSelectedAddressBeans.addAll(data)
                    if (mSelectedAddressBeans.isNotEmpty()) {
                        mBinding.tvProvince.text = "已设置"
                        mEditorViewModel.obPeriods.postValue(true)

                    } else {
                        mBinding.tvProvince.text = ""
                        mEditorViewModel.obPeriods.postValue(false)
                    }

                }
        }

        XPopup.Builder(this)
            .isViewMode(true)//对于只使用一次的弹窗，推荐设置这个true
            .popupPosition(PopupPosition.Bottom)
            .asCustom(mProvincePopupView)
            .show()

        mProvincePopupView?.setOnSwitchListener { position, data ->
            ARouter.getInstance().build(ARoutUtils.SwitchCommonActivity)
                .withString("title", "多省份展示")
                .withString("content", "多省份展示")
                .withString("dec", "开启“多省份展示”后，可直接返回上一页，选择多个省份。")
                .withBoolean("isOpen", mProvinceIsOpen)
                .navigation(this, 7)
        }
    }

    private val mLogos = mutableListOf<String>()
    /*private fun saveDataBase() {
        val cpName = mEditorViewModel.obCpname.get()
        if (cpName.isNullOrEmpty()) {
            AnimationUtils.setHintAnimation(mBinding.etName)
            showToast("请输入公司名称")
            return
        }
        val identification = mEditorViewModel.obName.get()
        if (identification.isNullOrEmpty() || identification.length < 15) {
            AnimationUtils.setHintAnimation(mBinding.etIndentification)
            showToast("请输入正确的信用代码")
            return
        }
        val phone = mEditorViewModel.obPhone.get()
        if (phone.isNullOrEmpty() || phone.length != 11) {
            AnimationUtils.setHintAnimation(mBinding.etPhone)
            showToast("请输入正确的手机号")
            return
        }
        if (mBnames.isEmpty()) {
            AnimationUtils.setHintAnimation(mBinding.tvBname)
            showToast("请设置主营")
            return
        }
        if (mProvince.isEmpty() || mDetailsAddress.isEmpty()) {
            AnimationUtils.setHintAnimation(mBinding.tvAddress)
            showToast("请设置地址")
            return
        }
        if (mSelectedCategoryBean.isEmpty()) {
            AnimationUtils.setHintAnimation(mBinding.tvCategory)
            showToast("请设置行业分类")
            return
        }
        if (mSelectedAddressBeans.isEmpty()) {
            AnimationUtils.setHintAnimation(mBinding.tvProvince)
            showToast("请设置展示省份")
            return
        }
        var count = 0
        if (mFactoryBeans.isEmpty()) {
            AnimationUtils.setHintAnimation(mBinding.tvFactory)
            showToast("请设置工厂展示")
            return
        } else {
            for (i in 0 until mFactoryBeans.size) {
                val type = mFactoryBeans[i].type
                if (type == "0") {
                    count++
                }
            }
        }
        if (count < 2) {
            showToast("请完善工厂展示")
        }
//        mBinding.tvSave.isEnabled = false
        var book = ""
        mSelectedAddressBeans.forEach { item -> book = "$book,${item.name}" }
        if (book.startsWith(",")) {
            book = book.drop(1)
        }
        val bnames = GsonUtils.toJson(mBnames)
        startLoading("保存中……")
        mBeans.forEach { item ->
            mLogos.add(item?.compressPath ?: item?.realPath ?: "")
        }
        lifecycleScope.launchWhenCreated {
//            withContext(myScope.coroutineContext) {
            val taskA = async { saveLogoBase() }
            val taskB = async { saveFactoryDataBase() }
            taskA.await()
            taskB.await()
            saveDoDataBase(mLogos, cpName, identification, phone, bnames, book)

            loadFinished()
            finish()
        }

    }*/

    /* private suspend fun saveLogoBase() {
         withContext(Dispatchers.IO) {
             if (mLogos.isNotEmpty()) {
                 val newPath =
                     MyUtils.getSDPath(this@OpenClientHFRActivity) + Constants.KEY_COMPANY_MEDIA_SYY
                 var logoName = ImageTypeUtil.getSuffixFromUrl(mLogos[0])
                 logoName = System.currentTimeMillis().toString() + logoName
                 FileUtils.copyFile(mLogos[0], newPath, logoName)
                 mLogos.clear()
                 mLogos.add("$newPath/$logoName")
             }
         }

     }

     private suspend fun saveFactoryDataBase() {
 //        val mFactoryStrings = mutableListOf<TVIVItemStringBean>()
         withContext(Dispatchers.IO) {
             for (i in 0 until mFactoryBeans.size) {
                 val image = mFactoryBeans[i].image
                 var newFilePath = image?.compressPath ?: image?.realPath
                 val oldFilePath = newFilePath
                 val newPath =
                     MyUtils.getSDPath(this@OpenClientHFRActivity) + Constants.KEY_COMPANY_MEDIA_SYY
                 var logoName = ImageTypeUtil.getSuffixFromUrl(newFilePath)
                 logoName = System.currentTimeMillis().toString() + logoName
                 FileUtils.copyFile(oldFilePath, newPath, logoName)
                 newFilePath = "$newPath/$logoName"
                 mFactoryBeans[i].image?.compressPath = newFilePath
                 mFactoryBeans[i].image?.path = newFilePath
                 mFactoryBeans[i].image?.realPath = newFilePath
             }
         }

     }*/

//    private suspend fun saveDoDataBase(
//        mLogos: MutableList<String>,
//        cpName: String,
//        identification: String,
//        phone: String,
//        bnames: String,
//        book: String
//    ) {
//        withContext(Dispatchers.IO) {
//            var categoryName = ""
//            mSelectedCategoryBean.forEach { item ->
//                val fcaid = item.fcaid
//                val cate = mCategoryBean.filter { category -> category.fcaid == fcaid }
//                categoryName = item.name
//                if (cate.isNotEmpty()) {
//                    categoryName = "${cate[0].name}-${item.name}"
//                }
//            }
//            val companyDraftItemBean = CompanyDraftItemBean(
//                id = if (mIntentItem == null) System.currentTimeMillis()
//                    .toString() else mIntentItem?.id
//                    ?: "",
//                logoMedia = mLogos,
//                name = cpName,
//                identification = identification,
//                phone = phone,
//                bnames = bnames,
//                province = mProvince,
//                city = mCity,
//                area = mArea,
//                prefecture = mTown,
//                address = mDetailsAddress,
//                category = mSelectedCategoryBean,
//                categoryName = categoryName,
//                book = book,
//                factoryMedia = mFactoryBeans,
//                mUserInfo?.id ?: "",
//                System.currentTimeMillis()
//            )
//            CompanyDraftDbHelper.insertFindCompany(
//                this@OpenClientHFRActivity,
//                companyDraftItemBean
//            )
//            if (mTempBeans.isNotEmpty()) {
//                val compressPath = mTempBeans[0]?.compressPath
//                FileUtils.deleteFile(compressPath)
//
//            }
//            mTempDeleteFactoryBeans.forEach { item ->
//                FileUtils.deleteFile(item)
//            }
//
//        }
//    }

    private fun aliUpNet() {
        val cpName = mEditorViewModel.obCpname.get()
        if (cpName.isNullOrEmpty()) {
            AnimationUtils.setHintAnimation(mBinding.etName)
            showToast("请输入公司名称")
            return
        }
        val identification = mEditorViewModel.obName.get()
        if (identification.isNullOrEmpty() || identification.length < 15) {
            AnimationUtils.setHintAnimation(mBinding.etIndentification)
            showToast("请输入正确的信用代码")
            return
        }
        val phone = mEditorViewModel.obPhone.get()
        if (phone.isNullOrEmpty() || phone.length != 11) {
            AnimationUtils.setHintAnimation(mBinding.etPhone)
            showToast("请输入正确的手机号")
            return
        }
        if (mBnames.isEmpty()) {
            AnimationUtils.setHintAnimation(mBinding.tvBname)
            showToast("请设置主营")
            return
        }
        if (mProvince.isEmpty() || mDetailsAddress.isEmpty()) {
            AnimationUtils.setHintAnimation(mBinding.tvAddress)
            showToast("请设置地址")
            return
        }
        if (mSelectedCategoryBean.isEmpty()) {
            AnimationUtils.setHintAnimation(mBinding.tvCategory)
            showToast("请设置行业分类")
            return
        }
        if (mSelectedAddressBeans.isEmpty()) {
            AnimationUtils.setHintAnimation(mBinding.tvProvince)
            showToast("请设置展示省份")
            return
        }
        var count = 0
        if (mFactoryBeans.isEmpty()) {
            AnimationUtils.setHintAnimation(mBinding.tvFactory)
            showToast("请设置工厂展示")
            return
        } else {
            for (i in 0 until mFactoryBeans.size) {
                val type = mFactoryBeans[i].type
                if (type == "0") {
                    count++
                }
            }
        }
        if (count < 2) {
            showToast("请完善工厂展示")
        }
        startLoading("申请中……")
        val mMedia = mutableListOf<LocalMedia?>()
        mMedia.clear()
        mMedia.addAll(mBeans)
        val conlist = mutableListOf<DisplayFacBean>()
        conlist.clear()
//        val borderString = GsonUtils.toJson(mDefaultBorderBean)
        mFactoryBeans.forEach { item ->
//            var border = item.border
//            if (item.border.isNullOrEmpty()) {
//                border = borderString
//            }
            val displayFacBean =
                DisplayFacBean(
                    item.image?.compressPath ?: item.image?.realPath,
                    item.type,
                    item.image?.compressPath ?: item.image?.realPath,
                    "${item.image?.width ?: 1080}",
                    "${item.image?.height ?: 1080}"
//                    , border = border
                )
            conlist.add(displayFacBean)
            mMedia.add(item.image)
        }
        lifecycleScope.launchWhenCreated {
            withContext(Dispatchers.IO) {
                YgxNetUtilsKt.partFilesToAli(
                    this@OpenClientHFRActivity, mSelectMedia = mMedia, uploadFileListener =
                        object : UploadFileListener {
                            override fun uploadSuccess(list: List<String>, listString: String) {
                                super.uploadSuccess(list, listString)
//                                val timeend = System.currentTimeMillis()
                                if (list.isNotEmpty() && list.size >= conlist.size + 1) {
                                    val image = list[0]

                                    conlist.forEachIndexed { index, displayFacBean ->
                                        displayFacBean.image = list[index + 1]
                                        displayFacBean.imageFirst = list[index + 1]

                                    }
                                    saveHfrCompany(
                                        image, phone, cpName, identification, conlist
                                    )
                                }
                            }

                            override fun uploadFailed(message: String) {
                                super.uploadFailed(message)
                                loadFinished()
                            }
                        })
            }
        }
//        LogUtils.e(mImages)
//        return aaa.toString()
    }

    private fun saveHfrCompany(
        image: String,
        phone: String,
        cpName: String,
        identification: String,
        contacts: MutableList<DisplayFacBean>
    ) {
        val bnames = GsonUtils.toJson(mBnames)
        val categorys = mutableListOf<CategorySubBean>()
        mSelectedCategoryBean.forEach { item ->
            val fcaid = item.fcaid
            val cate = mCategoryBean.filter { category -> category.fcaid == fcaid }
            var name = item.name
            if (cate.isNotEmpty()) {
                name = "${cate[0].name}-${item.name}"
            }
            categorys.add(CategorySubBean(name?:"", "${item.fcaid}", "${item.secaid}"))
        }
        val catrgory = CategoryMoreBean(if (mIsOpen) "1" else "0", categorys)
        val provinces = mutableListOf<NameBean>()
        mSelectedAddressBeans.forEach { item ->
            provinces.add(NameBean(item.name ?: ""))
        }
        val displayPro = DisplayPro(if (mProvinceIsOpen) "1" else "0", provinces)
        val body = ClientHFRReqBody(
            phone, cpName, image, mProvince, mCity, mArea, mTown, mDetailsAddress, bnames, "",
            "", identification, catrgory, null, null, contacts, displayPro
        )

        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                withContext(myScope.coroutineContext) {
                    viewModel.saveHengCompany(body)
                }
            parseResult(result)
        }
    }

    private fun parseResult(data: DataResult<BaseYgxRsp>) {
        loadFinished()
        data.onSuccess {
            onBizOK<ClientItemBean> { code, data, message, result ->
                data?.let {
                    message?.let { it1 -> showToast(it1) }
                    //保存地址数据方便下次使用
//                    SPStaticUtils.put(
//                        Constants.KEY_OPEN_CITY,
//                        "${mProvince}_${mCity}_${mArea}_${mTown}_$mDetailsAddress"
//                    )
                    //发消息通知 新增、修改 开户
                    LiveEventBus
                        .get(CompanyStateEvent::class.java)
                        .post(CompanyStateEvent(it, 5))
//                        .post(CompanyStateEvent(it, if (mIntentData == null) 0 else 4))
                    //发消息通知客户列表添加客户
                    LiveEventBus.get(ClientStateEvent::class.java)
                        .post(ClientStateEvent(data, 0))
//                    if (mIntentItem != null) {
//                        if (mTempBeans.isNotEmpty()) {
//                            val compressPath = mTempBeans[0]?.compressPath
//                            FileUtils.deleteFile(compressPath)
//                        }
//
//                        mTempDeleteFactoryBeans.forEach { item ->
//                            FileUtils.deleteFile(item)
//                        }
//
//                    }
                    finish()
                }

            }
            onBizError<Any> { code, message, data ->
                showToast(message)
//                showSaveDialog()
            }
        }
        data.onFailure {
            showToast("网络错误")
//            showSaveDialog()
        }
    }

//    private var mHintDialog: HintDialog? = null
//    private fun showSaveDialog() {
//        mHintDialog = HintDialog(this, "提示", "是否保存到草稿箱？", true, true, {
//            saveDataBase()
//        })
//        mHintDialog?.show()
//    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null) {
            return
        }
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {

                4 -> {
                    val list: ArrayList<String>? =
                        data.getStringArrayListExtra("introduce")
                    if (!list.isNullOrEmpty()) {
                        mBnames.clear()
                        mBnames.addAll(list)
                        if (mBnames.isNotEmpty()) {
                            var name = ""
                            mBnames.forEach { n ->
                                name = "$name、$n"
                            }
                            if (name.startsWith("、")) {
                                name = name.drop(1)
                            }
                            mBinding.tvBname.text = name
                        } else {
                            mBinding.tvBname.text = ""
                        }
                        mEditorViewModel.paramsSeting.postValue(mBnames.isNotEmpty())
                    }
                }

                5 -> {
                    mDetailsAddress = data.getStringExtra("detail_frist") ?: ""
                    mProvince = data.getStringExtra("province_frist") ?: ""
                    mCity = data.getStringExtra("city_frist") ?: ""
                    mArea = data.getStringExtra("area_frist") ?: ""
                    mTown = data.getStringExtra("town_frist") ?: ""
                    mBinding.tvAddress.text = "$mProvince$mCity$mArea$mTown$mDetailsAddress"
                    mEditorViewModel.addressShow.postValue(mDetailsAddress.isNotEmpty())

                }

                6 -> {
                    mIsOpen = data.getBooleanExtra("isOpen", false)
                    mCategoryPopupView?.setOpen(mIsOpen)
                }

                7 -> {
                    mProvinceIsOpen = data.getBooleanExtra("isOpen", false)
                    mProvincePopupView?.setOpen(mProvinceIsOpen)
                }

                8 -> {
                    val list: ArrayList<TVIVItemBean>? =
                        data.getParcelableArrayListExtra("media")
                    if (!list.isNullOrEmpty()) {
                        mFactoryBeans.clear()
                        mFactoryBeans.addAll(list)
                        mBinding.tvFactory.text = "已设置"
                    }
                    mEditorViewModel.moreTypeMedia.postValue(mFactoryBeans)
                }
//                9 -> {
//                    val list: ArrayList<CategoryPeriodsBody>? =
//                        data.getParcelableArrayListExtra("categoryDatas")
//                    if (!list.isNullOrEmpty()) {
//                        mPdAndCa.clear()
//                        mPdAndCa.addAll(list)
////                        mPdAndCa = GsonUtils.toJson(list)
//                        mBinding.tvProvince.text = "已设置"
//                        mEditorViewModel.obPeriods.postValue(true)
//
//                    } else {
//                        mPdAndCa.clear()
//                        mEditorViewModel.obPeriods.postValue(false)
//                        mBinding.tvProvince.text = ""
//                    }
//                }

            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        loadFinished()
        FileUtils.delAllFile(MyUtils.getSDPath(MyUtils.mContext) + "/suyiyong_o_video")
//        if (mHintDialog?.isShowing == true) {
//            mHintDialog?.dismiss()
//        }
    }

}

